package com.cjk.foundation.util;

import java.io.IOException;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.util.ArrayList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ShellUnit {
	
	private static String OS = System.getProperty("os.name").toLowerCase();  
	
	private static final Logger logger = LoggerFactory.getLogger(ShellUnit.class);

	private static void logDebug(String string) {
		if (logger.isDebugEnabled()) {
			logger.debug(string);
		}
	}

	public static boolean runShellCmd(String shellCmd) {
		if (OS.indexOf("win") >= 0) {
			logger.warn("The system don't support shell !!!");
			return false;
		}

		logger.info("shellCmd: " + shellCmd);
		Process process = null;
		boolean reVal = false;
		try {
			List<String> cmds = new ArrayList<String>();
			cmds.add("sh");
			cmds.add("-c");
			cmds.add(shellCmd);
			ProcessBuilder pb = new ProcessBuilder(cmds);
			process = pb.start();
			
			int exitValue = process.waitFor();
			logger.debug("extValue:{}", exitValue);
			if (0 != exitValue) {
				logDebug("exec shell cmd fail: " + shellCmd + ";" + exitValue);
				reVal = false;
			} else {
				reVal = true;
			}
		} catch (Exception e) {
			e.printStackTrace();
			reVal = false;
		} finally {
			try {
				if (process != null) {
					try {
						process.getErrorStream().close();
						process.getInputStream().close();
						process.getOutputStream().close();
					} catch (Exception e2) {
						e2.printStackTrace();
					}
				}
			} catch (Exception e2) {
				e2.printStackTrace();
			}
		}

		return reVal;
	}
	
    public static int runShellCmd(String shellCmd, List<String> strList) {
        logDebug("shellCmd: " + shellCmd);
        
        int ret = -1;
        String[] cmds = {"sh", "-c", shellCmd};
        
        Process pcs;
        LineNumberReader input = null;
        try {
            pcs = Runtime.getRuntime().exec(cmds,null,null);
            InputStreamReader ir = new InputStreamReader(pcs.getInputStream());
            input = new LineNumberReader(ir);
            String line = null;    
            while (strList != null && (line = input.readLine()) != null){
                strList.add(line);
            } 
            ret = pcs.waitFor();
            if (ret != 0) {
                logger.error("Failed to exectute cmd: {}, extValue:{}", cmds, ret);                
            } else {
                logger.info("cmd: {}, extValue:{}", cmds, ret);                
            }
            
        } catch (IOException e) {
            logger.error("IOException: {}", e);
        } catch (InterruptedException e) {
            logger.error("InterruptedException: {}", e);
        } finally {
            if(null != input){    
                try {
                    input.close();
                } catch (IOException e) {
                    logger.error("finally IOException: {}", e);
                }    
            }
        }
        
        return ret;
    }
    
	// tar -zcvf FileName.tar.gz DirName
	public static void gzipFile(String sourcePath, String targetName) {
		String shellCmd = "tar -zcvf " + targetName + " -C " + sourcePath + " .";
		runShellCmd(shellCmd);
	}

	// tar -zxvf /home/zjx/aa.tar.gz -C /home/zjx/pf
	public static void unGzipFile(String sourceName, String targetPath) {
		String shellCmd = "tar -zxvf " + sourceName + " -C " + targetPath;
		runShellCmd(shellCmd);
	}

	public static void deletePath(String path) {
		String shellCmd = "rm -rf " + path;
		runShellCmd(shellCmd);
	}

	public static void copyPath(String sourcePath, String targetPath) {
		String shellCmd = "cp -rf " + sourcePath + " " + targetPath;
		runShellCmd(shellCmd);
	}

	public static boolean ftpUploadFile(String host, int port, String username,
			String password, String localFile, String remoteFile) {
		String shellCmd = "wput -tries=2 -timeout=20 ";
		shellCmd = shellCmd + localFile + " ";
		shellCmd = shellCmd + "ftp://" + username + ":" + password;
		shellCmd = shellCmd + "@" + host + ":" + port + remoteFile;

		return runShellCmd(shellCmd);
	}

}
